<script lang="ts" setup>
import type { RowType } from '#/views/dashboard/admin/options';

import { Page, useVbenModal } from '@vben/common-ui';

import { Plus } from '@element-plus/icons-vue';
import { ElButton, ElPopconfirm } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteUserApi } from '#/api';
import { formOptions, gridOptions } from '#/views/dashboard/admin/options';

import Modal from './Modal.vue';

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Modal,
});

const openModal = (row: null | RowType) => {
  if (row) {
    formModalApi.setData({
      values: row,
    });
  } else {
    formModalApi.setData({
      values: {},
    });
  }
  formModalApi.open();
};

const handleDelete = (id: string) => {
  deleteUserApi({ id }).then(() => {
    gridApi.reload();
  });
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <ElButton :icon="Plus" type="primary" @click="openModal(null)">
          新增
        </ElButton>
      </template>
      <template #action="{ row }">
        <ElButton link type="primary" @click="openModal(row)">编辑</ElButton>
        <ElPopconfirm title="确认删除吗?" @confirm="handleDelete(row.id)">
          <template #reference>
            <ElButton link type="primary"> 删除 </ElButton>
          </template>
        </ElPopconfirm>
      </template>
    </Grid>
    <FormModal @submit="gridApi.reload" />
  </Page>
</template>
